package com.kgcx.order.service;

import com.kgcx.common.eum.OrderEnum;
import com.kgcx.common.utils.AuroraPush;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.order.domain.Order;
import com.kgcx.order.entity.OrderChangeMessage;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

public class OrderNotifyUserService {
    private static final String NOTIFY_USER_TYPE_JPUSH = "jpush"; // 极光APP消息推送
    private static final String NOTIFY_USER_TYPE_MQTT = "mqtt"; // MQTT长连接

    private static final Logger LOG = LoggerFactory.getLogger(OrderNotifyUserService.class);

    @Value("${kgcx.order.notify-user-type:jpush}")
    private String notifyUserType;
    @Autowired(required = false)
    private MqttClient mqttProducer;


    public void notifyUser(Order record, String msg) {
        try {
            if (NOTIFY_USER_TYPE_MQTT.equals(notifyUserType)) {
                notifyUserByMqtt(record, msg);
            } else if (NOTIFY_USER_TYPE_JPUSH.equals(notifyUserType)) {
                notifyUserByJpush(record, msg);
            } else {
                notifyUserByJpush(record, msg);
            }

            LOG.info(String.format("订单[%s]，给乘客[%d]推送订单状态变更信息成功，推送方式为%s。", record.getOrderNo(), record.getPlacingUserId(),
                    notifyUserType));
        } catch (Exception e) {
            LOG.error(String.format("订单[%s]，给乘客[%d]推送订单状态变更信息失败，推送方式为%s。", record.getOrderNo(), record.getPlacingUserId(),
                    notifyUserType), e);
        }
    }

    private void notifyUserByMqtt(Order record, String msg)
            throws MqttPersistenceException, MqttException {
        if (mqttProducer == null) {
            LOG.warn(String.format("订单[%s]，MQTT功能未开启，转为jpush推送。请确认kgcx.mqtt.enable配置属性的值是否为true。",
                    record.getOrderNo()));
            notifyUserByJpush(record, msg);
            return;
        }

        OrderChangeMessage mqMsg = new OrderChangeMessage(record.getOrderNo()
                , OrderEnum.CANCEL_ORDER, OrderChangeMessage.MESSAGE_TYPE_CANCLE, "乘客已取消订单", record.getPlacingUserId());
        String strTopic = OrderEnum.ORDER_STATE_TOPIC + "." + record.getPlacingUserId().toString();

        MqttMessage message = new MqttMessage();
        message.setQos(1);
        message.setRetained(false); // 是否是实时发送的消息
        message.setPayload(JsonUtil.toString(mqMsg).getBytes());

        MqttTopic topic = mqttProducer.getTopic(strTopic);
        topic.publish(message);
    }

    private void notifyUserByJpush(Order record, String msg) {
        // 发送通知
        AuroraPush.pushTargetForUser(String.valueOf(record.getPlacingUserId()), msg);

        OrderChangeMessage message = new OrderChangeMessage(record.getOrderNo()
                , OrderEnum.CANCEL_ORDER, OrderChangeMessage.MESSAGE_TYPE_CANCLE, "乘客已取消订单", record.getPlacingUserId());
//        String topic = OrderEnum.ORDER_STATE_TOPIC + "." + record.getPlacingUserId().toString();
        // 发送消息
//        AuroraPush.pushTargetMsgForUser(OrderEnum.ORDER_STATE_TOPIC, JsonUtil.toString(message),
//                String.valueOf(record.getPlacingUserId()), AuroraPush.PLATFORM_ANDROID);
    }
}
